﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Organization;
using TomNet.IMSC.Web.Common;
using TomNet.IMSC.Web.Filters;
using TomNet.IMSC.Web.Models.ApiParams;
using TomNet.Web.Mvc.UI;
using TomNet.Web.WebApi;

namespace TomNet.IMSC.Web.Controllers.API
{
    [Description("API-账户")]
    [ApiAuthentication]
    public class OrganizationController : BaseApiController
    {
        public ICustomerContract CustomerContract { get; set; }
        public ICustomerPhoneContract CustomerPhoneContract { get; set; }
        public IUsersContract UsersContract { get; set; }
        public IUsersRolesContract UsersRolesContract { get; set; }
        public IImageGroupContract ImageGroupContract { get; set; }
        public IImagesContract ImagesContract { get; set; }
        public IIntermediaryContract IntermediaryContract { get; set; }
        [Description("API-查找客户")]
        public IHttpActionResult ttGetCustomersList([FromBody]CustomersParamsModel entity)
        {
            int userid = BaseWebApiExt.GetUserIDByToken();
            bool IsDianZhang = UsersRolesContract.Entities.Count(p => p.IntermediaryRoleID == 1 && p.UserID == userid) > 0;
            bool IsHide = IntermediaryContract.GetByKey(UsersContract.GetByKey(userid).IntermediaryID).IsLocked;

            var query = (from m in CustomerContract.Entities
                         where m.UserID == entity.UserID && m.IsDeleted == false
                         select new CustomersListModel
                         {
                             Id = m.Id,
                             Name = m.Name,
                             Remark = m.Remark,
                             Sex = m.Sex,
                             PhoneList = (from m1 in CustomerPhoneContract.Entities
                                          where m1.CustomerID == m.Id
                                          orderby m1.Id
                                          select new CustomerPhoneModel
                                          {
                                              CustomerPhoneID = m1.Id,
                                              //Phone = m1.Phone,
                                              Phone = IsDianZhang || !IsHide ? m1.Phone : m1.Phone.Substring(0, 3) + "****" + m1.Phone.Substring(7),
                                              Remark = m1.Remark
                                          }).ToList()
                         });

            //条件搜索
            if (!string.IsNullOrWhiteSpace(entity.KeyWord))
            {
                query = query.Where(m => m.Name.Contains(entity.KeyWord));
            }

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderBy(m => m.Name);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((entity.PageIndex - 1) * entity.PageSize).Take(entity.PageSize)
                : Enumerable.Empty<CustomersListModel>().AsQueryable();// null;

            var result = new AjaxResultRow("成功", AjaxResultType.Success, query.ToList(), total);
            return Token(result, "");

        }


        [Description("API-添加客户")]
        public IHttpActionResult ttInsertNewCustomer([FromBody]CustomerParamsModel entity)
        {
            var result = new AjaxResult("添加成功", AjaxResultType.Success);

            if (entity == null)
            {
                result = new AjaxResult("添加失败", AjaxResultType.Error);
                return Token(result, "");
            }

            Customer model = new Customer();
            model.Name = entity.Name;
            model.Sex = entity.Sex;
            model.UserID = entity.UserID;
            
            //事务开始
            CustomerContract.Repository.UnitOfWork.BeginTransaction();

            int count = CustomerContract.Insert(model);

            if (count > 0)
            {
                var arrPhone = entity.CustomerPhoneList.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                if (arrPhone.Count() > 0)
                {
                    foreach (var item in arrPhone)
                    {
                        CustomerPhone temp = new CustomerPhone();
                        temp.CustomerID = model.Id;
                        temp.Phone = item;

                        int count2 = CustomerPhoneContract.Insert(temp);
                        if (count2 < 0)
                        {
                            result = new AjaxResult("添加失败", AjaxResultType.Error);
                            break;
                        }
                    }
                }
            }
            else
            {
                result = new AjaxResult("添加失败", AjaxResultType.Error);
            }


            //事务结束
            CustomerContract.Repository.UnitOfWork.Commit();


            return Token(result, "");
        }


        [Description("API-修改客户")]
        public IHttpActionResult ttUpdateCustomer([FromBody]CustomerEditParamsModel entity)
        {
            
            var result = new AjaxResult("修改成功", AjaxResultType.Success);

            if (entity == null)
            {
                result = new AjaxResult("修改失败", AjaxResultType.Error);
                return Token(result, "");
            }

            Customer model = CustomerContract.GetByKey(entity.CustomerID);

            if (model == null)
            {
                result = new AjaxResult("修改失败", AjaxResultType.Error);
                return Token(result, "");
            }
            
            //model.Name = entity.Name;
            //model.Sex = entity.Sex;
            //model.UserID = entity.UserID;

            //事务开始
            CustomerContract.Repository.UnitOfWork.BeginTransaction();

            
            var arrPhone = entity.CustomerPhoneList.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

            if (arrPhone.Count() > 0)
            {
                foreach (var item in arrPhone)
                {
                    CustomerPhone temp = new CustomerPhone();
                    temp.CustomerID = model.Id;
                    temp.Phone = item;

                    int count = CustomerPhoneContract.Insert(temp);
                    if (count < 0)
                    {
                        result = new AjaxResult("修改失败", AjaxResultType.Error);
                        break;
                    }
                }
            }
            

            //事务结束
            CustomerContract.Repository.UnitOfWork.Commit();


            return Token(result, "");
        }


        [Description("API-经纪人列表")]
        public IHttpActionResult ttGetUserList()
        {
            int UserID = BaseWebApiExt.GetUserIDByToken();
            int IntermediaryID = UsersContract.GetByKey(UserID).IntermediaryID;
            var query = (from m in UsersContract.Entities
                         where m.IntermediaryID == IntermediaryID && m.IsDeleted == false
                         select new
                         {
                             Id = m.Id,
                             Name = m.Name,
                             Phone = m.Phone,
                             Sex = m.Sex,
                             Portrait = m.Portrait,
                             IsShopkeeper = UsersRolesContract.Entities.Count(p => p.UserID == m.Id && p.IntermediaryRoleID == 1) > 0,
                         });

            var result = new AjaxResult("成功", AjaxResultType.Success, query.ToList());
            return Token(result, "");

        }

        [Description("API-修改经纪人资料")]
        public IHttpActionResult ttUpdateUser([FromBody]Users entity)
        {
            var result = new AjaxResult("成功", AjaxResultType.Success);

            if (entity == null)
            {
                result = new AjaxResult("失败", AjaxResultType.Error);
                return Token(result, "");
            }

            

            //事务开始
            CustomerContract.Repository.UnitOfWork.BeginTransaction();
            Users u = UsersContract.GetByKey(BaseWebApiExt.GetUserIDByToken());// entity.Id);
            u.Declaration = entity.Declaration;
            u.Name = entity.Name;
            u.OperationPeriod = entity.OperationPeriod;
            u.Portrait = entity.Portrait;
            u.Sex = entity.Sex;
            int count = UsersContract.Update(u);

            if (count > 0)
            {

            }
            else
            {
                result = new AjaxResult("失败", AjaxResultType.Error);
            }


            //事务结束
            CustomerContract.Repository.UnitOfWork.Commit();


            return Token(result, "");
        }

    }
}